<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.id ? `编辑${levelName}` : `新增${levelName}` }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item label="上级地区" v-if="parentNames">
            <span>{{ parentNames }}</span>
          </el-form-item>
          <el-form-item label="地区名称" prop="name">
            <el-input v-model="dataForm.name" clearable>
              <template v-if="dataForm.level == 1" slot="append">
                <el-select v-model="villArea" value-key="id" style="width:120px" clearable filterable>
                  <el-option v-for="item in villAreaLevelList" :value="item" :label="item.name"
                    :key="item.id"></el-option>
                </el-select>
              </template>

              <template v-else slot="suffix">
                {{ levelName }}
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="小区" prop="villageId">
            <el-select v-model="dataForm.villageId" filterable clearable :disabled="!(dataForm.level == 1)">
              <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input type="number" v-model="dataForm.sort"></el-input>
          </el-form-item>
          <el-form-item label="备 注 " prop="remark">
            <el-input type="textarea" v-model="dataForm.remark"></el-input>
          </el-form-item>
          <el-form-item label="楼栋长联系方式" prop="linkList" v-if="dataForm.level == 2">
            <div v-for="(item, index) in dataForm.linkList" :key="index" style="margin-bottom: 10px;">
              <el-row tag="div">
                <el-col :span="10"><el-input v-model="item.linkName" placeholder="姓名"></el-input></el-col>
                <el-col :span="1">
                  <div style="text-align: center;">-</div>
                </el-col>
                <el-col :span="13"><el-input type="number" v-model="item.linkPhone" placeholder="电话"></el-input></el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-row>
        <div class="tit" v-if="this.dataForm.level == 4">
          <h2>
            {{
              dataForm.id
              ? `编辑物业收费信息`
              : `新增物业收费信息`
            }}
          </h2>
        </div>
        <el-row v-if="this.dataForm.level == 4">
          <el-form-item label="房屋面积" prop="houseSpace">
            <el-input placeholder="请填写房屋面积（保留两位小数）" @blur="houseSpaceVerify(dataForm.houseSpace, 1)"
              v-model="dataForm.houseSpace" clearable>
              <span slot="suffix">平米</span>
            </el-input>
          </el-form-item>
          <el-form-item label="物业费每平米单价" prop="pmcPrice">
            <el-input placeholder="请输入单价（保留两位小数）" v-model="dataForm.pmcPrice"
              @blur="houseSpaceVerify(dataForm.pmcPrice, 2)" clearable>
              <span slot="suffix">元</span>
            </el-input>
          </el-form-item>
          <el-form-item label="个人物业费折扣" prop="pmcSingleDiscount">
            <el-input placeholder="示例:如打9折，请输入0.9" v-model="dataForm.pmcSingleDiscount"
              @blur="houseSpaceVerify(dataForm.pmcSingleDiscount, 3)" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="物业费到期时间" prop="pmcExpireDate">
            <el-date-picker v-model="dataForm.pmcExpireDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="物业费上一次缴费日期" prop="pmcLatestDate">
            <el-date-picker v-model="dataForm.pmcLatestDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-row>
        <div class="tit">
          <h2>
            {{
              dataForm.id
              ? `编辑就近Aed/消防设备/消防通道图`
              : `新增就近Aed/消防设备/消防通道图`
            }}
          </h2>
        </div>
        <el-row>
          <el-form-item label="消防通道图 " prop="fireExitPicture">
            <upload-img class="upload-img" @uploadFileList="getsiteUrl($event, 1)" folder="villageArea">
              <img v-if="dataForm.fireExitPicture" width="100%" :src="dataForm.fireExitPicture" alt="" />
              <div class="tip">
                <i class="el-icon-upload" v-if="!dataForm.fireExitPicture"></i>
                <div v-if="!dataForm.fireExitPicture" class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </upload-img>
          </el-form-item>
          <el-form-item label="消防通道图描述 " prop="fireExitDepiction">
            <el-input type="textarea" :rows="9" v-model="dataForm.fireExitDepiction"></el-input>
          </el-form-item>
          <el-form-item label="就近消防设备图" prop="fireEquipPicture">
            <upload-img class="upload-img" @uploadFileList="getsiteUrl($event, 2)" folder="villageArea">
              <img v-if="dataForm.fireEquipPicture" width="100%" :src="dataForm.fireEquipPicture" alt="" />
              <div class="tip">
                <i class="el-icon-upload" v-if="!dataForm.fireEquipPicture"></i>
                <div v-if="!dataForm.fireEquipPicture" class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </upload-img>
          </el-form-item>
          <el-form-item label="就近消防设备图描述 " prop="fireEquipDepiction">
            <el-input type="textarea" :rows="9" v-model="dataForm.fireEquipDepiction"></el-input>
          </el-form-item>
          <el-form-item label="就近aed图" prop="aedPicture">
            <upload-img class="upload-img" @uploadFileList="getsiteUrl($event, 3)" folder="villageArea">
              <img v-if="dataForm.aedPicture" width="100%" :src="dataForm.aedPicture" alt="" />
              <div class="tip">
                <i class="el-icon-upload" v-if="!dataForm.aedPicture"></i>
                <div v-if="!dataForm.aedPicture" class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </upload-img>
          </el-form-item>
          <el-form-item label="就近aed图描述 " prop="aedDepiction">
            <el-input type="textarea" v-model="dataForm.aedDepiction" :rows="8"></el-input>
          </el-form-item>
        </el-row>
        <div class="tit">
          <h2>单元户型结构图</h2>
        </div>
        <el-row>
          <el-row style="width: 98%;margin: 0 auto;">
            <UploadOssFile class="upload-oss-file-c" :list="fileList" :isSelect="false" :limit="10"
              @getImgVideo="getImgVideo" folder="serverImg"></UploadOssFile>
          </el-row>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import Region from "@/components/Region";
import VillageAreaApi from "@/api/address/villageArea";
import VillageApi from "@/api/address/village";
import { endsWith } from "lodash-es";
import UploadImg from "@/components/UploadImg";
import UploadOssFile from "../../components/UploadOssFile.vue";
export default {
  components: {
    Region,
    UploadImg,
    UploadOssFile
  },
  data() {
    return {
      dataForm: {
        id: "",
        parentId: "",
        name: "",
        // villAreaCode:"",
        level: "",
        sort: "",
        villageId: "",
        remark: "",
        fireExitPicture: "", //消防通道图
        fireExitDepiction: "", //消防通道图描述”
        fireEquipPicture: "", //就近消防设备图
        fireEquipDepiction: "", //就近消防设备图描述
        aedPicture: "", //就近aed图
        aedDepiction: "", //就近aed图描述
        houseStructImgs: [],
        houseSpace: '',
        pmcPrice: '',
        pmcSingleDiscount: '',
        pmcExpireDate: '',
        pmcLatestDate: '',
        linkList: [{ linkName: '', linkPhone: '' }, { linkName: '', linkPhone: '' }]
      },
      villArea: null, //选中单元或者层的id
      villAreaLevelList: [
        // {id:1,name:"栋"},
        { id: 1, name: "栋" },
        { id: 2, name: "楼" }
      ],
      villageList: [],
      loadingIns: false,
      roleRules: {
        name: [{ required: true, message: "请输入地区名称", trigger: "blur" }],
        level: [
          { required: true, message: "请选择地区层级", trigger: "change" }
        ]
      },
      parentNames: "",
      fileList: []
    };
  },
  computed: {
    levelName() {
      switch (String(this.dataForm.level)) {
        case "1":
          return "栋/楼";
        case "2":
          return "单元";
        case "3":
          return "层";
        case "4":
          return "";
      }
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      const { id, parentId, level, parentNames, villageId } = this.$route.query;
      villageId && (this.dataForm.villageId = Number(villageId));
      parentNames && (this.parentNames = parentNames);
      if (id) {
        this.dataForm.id = id;
        this.getData();
      } else {
        if (parentId) {
          this.dataForm.level = level;
          this.dataForm.parentId = parentId;
        } else {
          this.dataForm.level = 1;
          this.dataForm.parentId = "";
        }
      }
      this.getVillageList();
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    houseSpaceVerify(val, i) {
      const regex = /^\d+(\.\d{1,2})?$/;
      if (!regex.test(val)) {

        this.$message.error("只能输入整数或小数")
        switch (i) {
          case 1:
            this.dataForm.houseSpace = ''
            break;
          case 2:
            this.dataForm.pmcPrice = ''
            break;
          case 3:
            this.dataForm.pmcSingleDiscount = ''
            break;
        }
      };
    },
    async getData() {
      const {
        dataForm: { id },
        villAreaLevelList
      } = this;
      const { data } = await VillageAreaApi.getVillageAreaInfo({ id: id });
      const suffix = data.name.at(-1);
      if (data.level == 1) {
        if (suffix === "栋" || suffix === "楼") {
          this.villArea =
            suffix === "栋" ? villAreaLevelList[0] : villAreaLevelList[1];
          data.name = data.name.split("");
          data.name.pop();
          data.name = data.name.join("");
        }
      } else {
        if (
          (data.level == 2 && data.name.endsWith("单元")) ||
          (suffix === "层" && data.level == 3) ||
          (suffix === "号" && data.level == 4)
        ) {
          data.name = data.name.split("");
          if (data.level == 2) {
            data.name = data.name.slice(0, -2);
          } else if (data.level == 3) {
            data.name.pop();
          } else {
            data.name = data.name.slice(0, -3);
          }
          data.name = data.name.join("");
        }
      }
      if (data.level == 2) {
        if (data.linkList.length === 0) {
          data.linkList = [{ linkName: '', linkPhone: '' }, { linkName: '', linkPhone: '' }];
        } else if (data.linkList.length === 1) {
          data.linkList.push({ linkName: '', linkPhone: '' });
        }
      }
      this.$Utils.bindingBean(this.dataForm, data);
      if (this.dataForm.houseStructImgs != null && this.dataForm.houseStructImgs.length > 0) {
        this.fileList = JSON.parse(
          JSON.stringify(this.dataForm.houseStructImgs || [])
        )
          .split(",")
          .map(url => ({ url, type: 1 }));
      }
    },
    async getVillageList() {
      const { data } = await VillageApi.villageList();
      this.villageList = data || [];
    },
    async sureClick() {
      await this.$refs.dataForm.validate();

      const { dataForm, villArea } = this;
      const { level, villageId, id } = dataForm;
      if (level == 1 && !villageId) return this.$message.error("请选择小区");

      await this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT);

      let linkList = this.processLinkList(this.dataForm.linkList)
      if (linkList === false) {
        this.$message.error('请将楼栋长信息填写完整')
        return false
      }
      
      let params = { ...dataForm };

      params.linkList = linkList

      if (linkList == null) {
        delete params.linkList
      }

      params.houseStructImgs = this.dataForm.houseStructImgs.length > 0 ? this.dataForm.houseStructImgs.map(item => item.url).join(",") : '';

      if (level == 1 && villArea) {
        const suffix = params.name.at(-1);
        suffix !== "栋" && suffix !== "楼" && (params.name = params.name + villArea.name);
      } else if (level == 2) {
        !params.name.endsWith("单元") && (params.name = params.name + "单元");
      } else if (level == 3) {
        !params.name.endsWith("层") && (params.name = params.name + "层");
      } else if (level == 4) {
        // !params.name.endsWith("门牌号")&&(params.name = params.name+"门牌号")
      }
      if (id) {
        this.editData(params);
      } else {
        delete params.id;
        this.addData(params);
      }
    },

    async addData(params) {
      await VillageAreaApi.addVillageArea(params);
      this.$Utils.notifySuccess();
      this.returnList();
    },

    async editData(params) {
      await VillageAreaApi.editVillageArea(params);
      this.$Utils.notifySuccess();
      this.returnList();
    },

    processLinkList(linkList) {

      const [first, second] = linkList;
      const isComplete_true = (obj) => obj.linkName && obj.linkPhone;
      // 判断两个对象是否都填写完整
      if (isComplete_true(first) && isComplete_true(second)) {
        return linkList; // 或 return second; 都可
      }
      if (isComplete_true(first)) {
        return [first]

      }
      if (isComplete_true(second)) {
        return [second]
      }

      // 检查是否两个对象都为空
      const allEmpty = (obj) => !obj.linkName && !obj.linkPhone;
      if (allEmpty(first) && allEmpty(second)) {
        return null; // 两个对象都为空，返回 null
      }

      for (const obj of linkList) {
        if ((obj.linkName && !obj.linkPhone) || (!obj.linkName && obj.linkPhone)) {
          return false
        }
      }
    },

    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.push({ path: "/address/villageAreaManagement" });
    },

    getsiteUrl(val, i) {
      if (val.length > 0) {
        this.$Utils.notifySuccess("上传成功");
      }
      switch (i) {
        case 1:
          this.dataForm.fireExitPicture = val[0];
          break;
        case 2:
          this.dataForm.fireEquipPicture = val[0];
          break;
        case 3:
          this.dataForm.aedPicture = val[0];

          break;
      }
    },

    // 获取上传的文件列表
    getImgVideo(val) {
      this.dataForm.houseStructImgs = val;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";

.upload-oss-file-c {
  &::v-deep .img-video-wrapper {
    .drag {
      .content {
        margin-bottom: 10px;
      }
    }
  }
}
</style>
